#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mount.h>

#define SD_DEV_A_R		"/dev/sda"
#define SD_DEV_B_R		"/dev/sdb"
#define SD_DEV_C_R		"/dev/sdc"
#define SD_DEV_D_R		"/dev/sdd"
#define SD_DEV_A		"/dev/sda1"
#define SD_DEV_B		"/dev/sdb1"
#define SD_DEV_C		"/dev/sdc1"
#define SD_DEV_D		"/dev/sdd1"
#define SD_DIR_P		"/mnt/sd"
#define SD_MOUNT_PARAM	"-o codepage=936,iocharset=gb2312"
#define SD_MOUNT_PARAM_P	"codepage=936,iocharset=gb2312"

static int sd_api_try_mount_dev(const char *first,const char *second,char *dev_path)
{
	//printf("first:[%p], second:[%p], dev_path:[%s]\n",first,second,dev_path);

	if(first==NULL||second==NULL||dev_path==NULL) //; -- 一个分号引发的血案，花了将近30分钟才发现
	{
		return -1;
	}

	dev_path[0]=0; // default fail
	if(mount(first,"/tmp","vfat",MS_SYNCHRONOUS,SD_MOUNT_PARAM_P)==0)
		strcpy(dev_path, first); 
	if(mount(second,"/tmp","vfat",MS_SYNCHRONOUS,SD_MOUNT_PARAM_P)==0)
		strcpy(dev_path, second);
	else 
	{
		perror("mount error:");
		return -1;
	}
#if 0
	if(strlen(dev_path)>0)
		umount("/tmp");
#endif

	return 0;
}

int main(int argc, char *argv[])
{
	int ret = -1;
	int sd_idx = 0;
	char dev_path[32]={0};

	for(sd_idx=0;sd_idx<4;sd_idx++)
	{
	switch (sd_idx) {
		case 0:	
			ret = sd_api_try_mount_dev(SD_DEV_A,SD_DEV_A_R,dev_path);
			break;
		case 1:	
			ret = sd_api_try_mount_dev(SD_DEV_B,SD_DEV_B_R,dev_path);
			break;
		case 2:	
			ret = sd_api_try_mount_dev(SD_DEV_C,SD_DEV_C_R,dev_path);
			break;
		case 3:
			ret = sd_api_try_mount_dev(SD_DEV_D,SD_DEV_D_R,dev_path);
			break;
		default: break;
	}
	
	if(ret < 0 || strlen(dev_path)==0)
		printf("don't find valid dev_node sd_idx:%d\n",sd_idx);
	else 
		printf("sd_api_find_dev_node sd_idx: %d dev_path:%s\n", sd_idx, dev_path);
	}

	return 0;
}
